<?php
class UniqueUsernameField extends TextField {
    protected $extraClasses = array('alphanumeric' => 'alphanumeric');
	
	private static $allowed_actions = array(
        'check_unique_username'
    );
	
	/**
     * The url to use as the check unique username
     * @var string
     */
    protected $checkUniqueUsernameURL;

	public function __construct($name, $title = null, $value = '', $maxLength = null, $form = null) {
		Requirements::javascript(THIRDPARTY_DIR . '/jquery/jquery.js');
        Requirements::javascript('member/javascript/UniqueUsernameField.min.js');
		parent::__construct($name, $title, $value, $maxLength, $form);
	}
	
	function getAttributes() {
        return array_merge(
            parent::getAttributes(), array(
            	'rel' => 'uniqueusername',
                'data-url' => $this->getCheckUniqueUsernameURL(),
                'autocomplete' => 'off'
            )
        );
    }
	
	function Type() {
		return 'uniqueusername text';
	}
	
	/**
     * Set the URL used to check unique username.
     * 
     * @param string $URL The URL used for check unique username.
     */
    public function setCheckUniqueUsernameURL($url) {
        $this->checkUniqueUsernameURL = $url;
    }
	
	/**
     * Get the URL used to check unique username.
     *  
     * @return The URL used for check unique username.
     */
    public function getCheckUniqueUsernameURL() {

        if (!empty($this->checkUniqueUsernameURL)){
            return $this->checkUniqueUsernameURL;
		}

        // Attempt to link back to itself
        return $this->Link('check_unique_username');
    }
	
    function validate($validator) {
        if(Member::get()->find('Username', Convert::raw2sql($this->value)) || SiteTree::get_by_link($this->value) || strtolower($this->value) == 'home') {
            $validator->validationError($this->name, _t('UniqueUsernameField.USERNAME_NOT_UNIQUE', "The username is already used by other member"));
            return false;
        }
        return true;
    }

	/**
     * Handle a request for unique username checking.
     * 
     * @param HTTPRequest $request The request to handle.
     * @return Valid unique username result
     */
    function check_unique_username(HTTPRequest $request) {
    	$data = array('result' => 'error', 'msg' => _t('UniqueUsernameField.USERNAME_NOT_UNIQUE', "The username is already used by other member"));
		if(!(Member::get()->find('Username', Convert::raw2sql($request->getVar('username'))) || SiteTree::get_by_link($request->getVar('username')) || strtolower($request->getVar('username')) == 'home')) {
			$data = array('result' => 'success', 'msg' => _t('UniqueUsernameField.USERNAME_VALID', "The username is valid"));
		}
        // the response body
        return Convert::array2json($data);
    }
}
?>
